package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"mini/miniapi/internal/types"
	"mini/pkg"
	"net/http"
)

type LoginMiddleware struct {
}

func NewLoginMiddleware() *LoginMiddleware {
	return &LoginMiddleware{}
}

func (m *LoginMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		get := r.Header.Get("token")
		if get == "" {
			resp := types.Response{
				Message: "暂未登录",
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		token, s := pkg.GetToken(get)
		if s != "" {
			resp := types.Response{
				Message: s,
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		s2 := token["user"].(string)
		r.ParseForm()
		r.Form.Set("userId", s2)
		// Passthrough to next handler if need
		next(w, r)
	}
}
